<template>
  <div id="body">
    <h1>编写一个通用的事件监听函数</h1>
    <h2 id="btn">按钮</h2>

    <div class="list" id="d1">
      <a href="#">a1</a>
      <a href="#">a2</a>
      <a href="#">a3</a>
    </div>
  </div>
</template>

<script setup>
setTimeout(() => {
  // 获取dom元素
  const body = document.getElementById('body')
  const btnDom = document.getElementById('btn')
  const d1 = document.getElementById('d1')
  //   给该元素添加一个事件
  handleFn(btnDom, 'click', function (e) {
    alert(this.innerHTML)
  })
  handleFn(body, 'click', e => {
    console.log('body')
  })
  handleFn(
    d1,
    'click',
    function (e) {
      const target = e.target
      e.stopPropagation()
      alert(this.innerHTML)
    },
    'a'
  )
}, 0)

function handleFn(elem, type, fn, selector) {
  elem.addEventListener(type, e => {
    const target = e.target
    if (selector) {
      // 事件代理
      if (target.matches(selector)) {
        fn.call(target, e)
      }
    } else {
      // 普通函数
      fn.call(target, e)
    }
  })
}
</script>

<style scoped lang="scss">
.list {
  a {
    display: block;
  }
}
</style>
